<template>
  <div class="user-detail">
    <el-card class="detail-card">
      <!-- 页面标题和返回按钮 -->
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button link @click="goBack">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <span class="title">用户详情</span>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleEdit" v-permission="'system:user:edit'">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete" v-permission="'system:user:delete'">
              删除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
            <el-descriptions-item label="昵称">{{ userInfo.nickname }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="userInfo.status === 'active' ? 'success' : 'danger'">
                {{ userInfo.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ userInfo.createTime }}</el-descriptions-item>
            <el-descriptions-item label="最后登录时间">{{ userInfo.lastLoginTime }}</el-descriptions-item>
            <el-descriptions-item label="最后登录IP">{{ userInfo.lastLoginIp }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ userInfo.remark || '-' }}</el-descriptions-item>
          </el-descriptions>

          <!-- 角色信息 -->
          <div class="section-title">角色信息</div>
          <el-table :data="userInfo.roles" border style="width: 100%">
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="code" label="角色编码" />
            <el-table-column prop="description" label="角色描述" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" />
          </el-table>

          <!-- 部门信息 -->
          <div class="section-title">部门信息</div>
          <el-table :data="userInfo.departments" border style="width: 100%">
            <el-table-column prop="name" label="部门名称" />
            <el-table-column prop="code" label="部门编码" />
            <el-table-column prop="leader" label="负责人" />
            <el-table-column prop="phone" label="联系电话" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
          </el-table>

          <!-- 岗位信息 -->
          <div class="section-title">岗位信息</div>
          <el-table :data="userInfo.positions" border style="width: 100%">
            <el-table-column prop="name" label="岗位名称" />
            <el-table-column prop="code" label="岗位编码" />
            <el-table-column prop="description" label="岗位描述" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" />
          </el-table>
        </el-tab-pane>

        <!-- 操作日志 -->
        <el-tab-pane label="操作日志" name="logs">
          <div class="search-bar">
            <el-form :model="logSearchForm" inline>
              <el-form-item label="操作类型">
                <el-select v-model="logSearchForm.type" placeholder="请选择操作类型" clearable>
                  <el-option label="登录" value="login" />
                  <el-option label="新增" value="create" />
                  <el-option label="修改" value="update" />
                  <el-option label="删除" value="delete" />
                </el-select>
              </el-form-item>
              <el-form-item label="操作时间">
                <el-date-picker
                  v-model="logSearchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleLogSearch">搜索</el-button>
                <el-button @click="handleLogReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            v-loading="logLoading"
            :data="logList"
            border
            style="width: 100%"
          >
            <el-table-column prop="type" label="操作类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getLogTypeTag(row.type)">{{ getLogTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="操作描述" show-overflow-tooltip />
            <el-table-column prop="ip" label="IP地址" width="140" />
            <el-table-column prop="location" label="操作地点" width="140" />
            <el-table-column prop="browser" label="浏览器" width="140" />
            <el-table-column prop="os" label="操作系统" width="140" />
            <el-table-column prop="createTime" label="操作时间" width="180" />
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="logPage.current"
              v-model:page-size="logPage.size"
              :total="logPage.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleLogSizeChange"
              @current-change="handleLogCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 登录历史 -->
        <el-tab-pane label="登录历史" name="login-history">
          <div class="search-bar">
            <el-form :model="loginSearchForm" inline>
              <el-form-item label="登录状态">
                <el-select v-model="loginSearchForm.status" placeholder="请选择登录状态" clearable>
                  <el-option label="成功" value="success" />
                  <el-option label="失败" value="failed" />
                </el-select>
              </el-form-item>
              <el-form-item label="登录时间">
                <el-date-picker
                  v-model="loginSearchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleLoginSearch">搜索</el-button>
                <el-button @click="handleLoginReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            v-loading="loginLoading"
            :data="loginList"
            border
            style="width: 100%"
          >
            <el-table-column prop="status" label="登录状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                  {{ row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ip" label="IP地址" width="140" />
            <el-table-column prop="location" label="登录地点" width="140" />
            <el-table-column prop="browser" label="浏览器" width="140" />
            <el-table-column prop="os" label="操作系统" width="140" />
            <el-table-column prop="message" label="登录信息" show-overflow-tooltip />
            <el-table-column prop="createTime" label="登录时间" width="180" />
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="loginPage.current"
              v-model:page-size="loginPage.size"
              :total="loginPage.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleLoginSizeChange"
              @current-change="handleLoginCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 数据统计 -->
        <el-tab-pane label="数据统计" name="statistics">
          <!-- 统计卡片 -->
          <div class="statistics-cards">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card shadow="hover" class="statistics-card">
                  <template #header>
                    <div class="card-header">
                      <span>总登录次数</span>
                      <el-tooltip content="用户累计登录次数" placement="top">
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="card-value">{{ statistics.totalLogins }}</div>
                  <div class="card-footer">
                    <span>较上月</span>
                    <span :class="['trend', statistics.loginTrend >= 0 ? 'up' : 'down']">
                      {{ Math.abs(statistics.loginTrend) }}%
                      <el-icon>
                        <component :is="statistics.loginTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                      </el-icon>
                    </span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card shadow="hover" class="statistics-card">
                  <template #header>
                    <div class="card-header">
                      <span>活跃天数</span>
                      <el-tooltip content="最近30天内的活跃天数" placement="top">
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="card-value">{{ statistics.activeDays }}</div>
                  <div class="card-footer">
                    <span>较上月</span>
                    <span :class="['trend', statistics.activeTrend >= 0 ? 'up' : 'down']">
                      {{ Math.abs(statistics.activeTrend) }}%
                      <el-icon>
                        <component :is="statistics.activeTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                      </el-icon>
                    </span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card shadow="hover" class="statistics-card">
                  <template #header>
                    <div class="card-header">
                      <span>平均在线时长</span>
                      <el-tooltip content="最近30天平均每次登录在线时长" placement="top">
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="card-value">{{ statistics.avgOnlineTime }}分钟</div>
                  <div class="card-footer">
                    <span>较上月</span>
                    <span :class="['trend', statistics.onlineTrend >= 0 ? 'up' : 'down']">
                      {{ Math.abs(statistics.onlineTrend) }}%
                      <el-icon>
                        <component :is="statistics.onlineTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                      </el-icon>
                    </span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card shadow="hover" class="statistics-card">
                  <template #header>
                    <div class="card-header">
                      <span>最后活跃时间</span>
                      <el-tooltip content="用户最后一次操作时间" placement="top">
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="card-value">{{ statistics.lastActiveTime }}</div>
                  <div class="card-footer">
                    <span>距现在</span>
                    <span>{{ statistics.lastActiveDuration }}</span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 图表区域 -->
          <div class="statistics-charts">
            <el-row :gutter="20">
              <!-- 登录趋势图 -->
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>登录趋势</span>
                      <el-radio-group v-model="loginTrendType" size="small">
                        <el-radio-button label="week">近7天</el-radio-button>
                        <el-radio-button label="month">近30天</el-radio-button>
                      </el-radio-group>
                    </div>
                  </template>
                  <div class="chart-container" ref="loginTrendChartRef"></div>
                </el-card>
              </el-col>
              <!-- 活跃度分析图 -->
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>活跃度分析</span>
                      <el-select v-model="activeAnalysisType" size="small">
                        <el-option label="按小时" value="hour" />
                        <el-option label="按星期" value="week" />
                      </el-select>
                    </div>
                  </template>
                  <div class="chart-container" ref="activeAnalysisChartRef"></div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20" class="mt-20">
              <!-- 登录设备分布 -->
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>登录设备分布</span>
                    </div>
                  </template>
                  <div class="chart-container" ref="deviceDistChartRef"></div>
                </el-card>
              </el-col>
              <!-- 登录地区分布 -->
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>登录地区分布</span>
                    </div>
                  </template>
                  <div class="chart-container" ref="locationDistChartRef"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 安全中心 -->
        <el-tab-pane label="安全中心" name="security">
          <!-- 安全评分 -->
          <div class="security-score">
            <el-card class="score-card">
              <div class="score-header">
                <span class="title">安全评分</span>
                <el-tooltip content="根据账号安全设置和登录行为综合评估" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <div class="score-content">
                <div class="score-circle">
                  <el-progress
                    type="dashboard"
                    :percentage="securityScore"
                    :color="getScoreColor"
                    :stroke-width="8"
                  >
                    <template #default="{ percentage }">
                      <div class="score-value">
                        <span class="number">{{ percentage }}</span>
                        <span class="label">分</span>
                      </div>
                    </template>
                  </el-progress>
                </div>
                <div class="score-tips">
                  <p class="main-tip">{{ getScoreTip }}</p>
                  <p class="sub-tip">建议您及时完善以下安全设置</p>
                  <ul class="tip-list">
                    <li v-for="(tip, index) in securityTips" :key="index">
                      <el-icon><Warning /></el-icon>
                      {{ tip }}
                    </li>
                  </ul>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 安全设置 -->
          <div class="security-settings">
            <el-card class="settings-card">
              <template #header>
                <div class="card-header">
                  <span>安全设置</span>
                </div>
              </template>
              <el-form label-width="120px">
                <!-- 登录密码 -->
                <el-form-item label="登录密码">
                  <div class="setting-item">
                    <div class="setting-info">
                      <span class="label">定期修改密码可以保护账号安全</span>
                      <span class="value">上次修改时间：{{ securitySettings.lastPasswordChange }}</span>
                    </div>
                    <el-button type="primary" link @click="handleChangePassword">
                      修改密码
                    </el-button>
                  </div>
                </el-form-item>

                <!-- 手机绑定 -->
                <el-form-item label="手机绑定">
                  <div class="setting-item">
                    <div class="setting-info">
                      <span class="label">已绑定手机：{{ maskPhone(securitySettings.phone) }}</span>
                      <span class="value">可用于登录和找回密码</span>
                    </div>
                    <el-button type="primary" link @click="handleChangePhone">
                      修改手机
                    </el-button>
                  </div>
                </el-form-item>

                <!-- 邮箱绑定 -->
                <el-form-item label="邮箱绑定">
                  <div class="setting-item">
                    <div class="setting-info">
                      <span class="label">已绑定邮箱：{{ maskEmail(securitySettings.email) }}</span>
                      <span class="value">可用于登录和找回密码</span>
                    </div>
                    <el-button type="primary" link @click="handleChangeEmail">
                      修改邮箱
                    </el-button>
                  </div>
                </el-form-item>

                <!-- 登录保护 -->
                <el-form-item label="登录保护">
                  <div class="setting-item">
                    <div class="setting-info">
                      <span class="label">开启后，新设备登录需要验证</span>
                      <span class="value">当前状态：{{ securitySettings.loginProtection ? '已开启' : '未开启' }}</span>
                    </div>
                    <el-switch
                      v-model="securitySettings.loginProtection"
                      @change="handleToggleLoginProtection"
                    />
                  </div>
                </el-form-item>

                <!-- 异常登录提醒 -->
                <el-form-item label="异常登录提醒">
                  <div class="setting-item">
                    <div class="setting-info">
                      <span class="label">开启后，检测到异常登录将发送提醒</span>
                      <span class="value">当前状态：{{ securitySettings.loginAlert ? '已开启' : '未开启' }}</span>
                    </div>
                    <el-switch
                      v-model="securitySettings.loginAlert"
                      @change="handleToggleLoginAlert"
                    />
                  </div>
                </el-form-item>

                <!-- 登录设备管理 -->
                <el-form-item label="登录设备管理">
                  <div class="setting-item">
                    <div class="setting-info">
                      <span class="label">管理已登录的设备，可强制下线</span>
                      <span class="value">当前在线设备：{{ securitySettings.onlineDevices }}台</span>
                    </div>
                    <el-button type="primary" link @click="handleManageDevices">
                      管理设备
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </el-card>
          </div>

          <!-- 最近登录记录 -->
          <div class="recent-logins">
            <el-card class="logins-card">
              <template #header>
                <div class="card-header">
                  <span>最近登录记录</span>
                  <el-button type="primary" link @click="handleViewAllLogins">
                    查看全部
                  </el-button>
                </div>
              </template>
              <el-table :data="recentLogins" border style="width: 100%">
                <el-table-column prop="loginTime" label="登录时间" width="180" />
                <el-table-column prop="device" label="登录设备" width="180" />
                <el-table-column prop="location" label="登录地点" width="180" />
                <el-table-column prop="ip" label="IP地址" width="140" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                      {{ row.status === 'success' ? '成功' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" show-overflow-tooltip />
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑用户"
      width="600px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入原密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备管理对话框 -->
    <el-dialog
      v-model="deviceDialogVisible"
      title="登录设备管理"
      width="800px"
    >
      <el-table :data="deviceList" border style="width: 100%">
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="deviceType" label="设备类型" />
        <el-table-column prop="loginTime" label="最后登录时间" width="180" />
        <el-table-column prop="location" label="登录地点" width="180" />
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'online' ? 'success' : 'info'">
              {{ row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'online'"
              type="danger"
              link
              @click="handleForceLogout(row)"
            >
              强制下线
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, QuestionFilled, Warning } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getUserDetail,
  updateUser,
  deleteUser,
  getUserLogs,
  getUserLoginHistory,
  getUserDepartments,
  getUserPositions,
  getUserStatistics,
  getUserSecuritySettings,
  updateUserSecuritySettings,
  changeUserPassword,
  getUserDevices,
  forceUserLogout
} from '@/api/user'

const route = useRoute()
const router = useRouter()
const userId = route.params.id

// 当前激活的标签页
const activeTab = ref('basic')

// 用户信息
const userInfo = ref({})
const dialogVisible = ref(false)
const userFormRef = ref(null)
const userForm = reactive({
  nickname: '',
  phone: '',
  email: '',
  status: '',
  remark: ''
})

// 表单验证规则
const userRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 操作日志相关
const logLoading = ref(false)
const logList = ref([])
const logSearchForm = reactive({
  type: '',
  dateRange: []
})
const logPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 登录历史相关
const loginLoading = ref(false)
const loginList = ref([])
const loginSearchForm = reactive({
  status: '',
  dateRange: []
})
const loginPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 统计数据
const statistics = reactive({
  totalLogins: 0,
  loginTrend: 0,
  activeDays: 0,
  activeTrend: 0,
  avgOnlineTime: 0,
  onlineTrend: 0,
  lastActiveTime: '',
  lastActiveDuration: ''
})

// 图表相关
const loginTrendChartRef = ref(null)
const activeAnalysisChartRef = ref(null)
const deviceDistChartRef = ref(null)
const locationDistChartRef = ref(null)
let loginTrendChart = null
let activeAnalysisChart = null
let deviceDistChart = null
let locationDistChart = null

// 图表类型选择
const loginTrendType = ref('week')
const activeAnalysisType = ref('hour')

// 安全中心相关
const securityScore = ref(85)
const securityTips = ref([
  '建议开启登录保护，提高账号安全性',
  '建议绑定手机号，方便找回密码',
  '建议定期修改密码，保护账号安全'
])

// 安全设置
const securitySettings = reactive({
  lastPasswordChange: '',
  phone: '',
  email: '',
  loginProtection: false,
  loginAlert: false,
  onlineDevices: 0
})

// 最近登录记录
const recentLogins = ref([])

// 密码修改相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 设备管理相关
const deviceDialogVisible = ref(false)
const deviceList = ref([])

// 计算安全评分颜色
const getScoreColor = computed(() => {
  if (securityScore.value >= 80) return '#67C23A'
  if (securityScore.value >= 60) return '#E6A23C'
  return '#F56C6C'
})

// 计算安全评分提示
const getScoreTip = computed(() => {
  if (securityScore.value >= 80) return '账号安全状态良好'
  if (securityScore.value >= 60) return '账号安全状态一般'
  return '账号安全状态较差'
})

// 获取用户详情
const getUserInfo = async () => {
  try {
    const { data } = await getUserDetail(userId)
    userInfo.value = data
  } catch (error) {
    console.error('获取用户详情失败:', error)
  }
}

// 获取用户部门信息
const getDepartments = async () => {
  try {
    const { data } = await getUserDepartments(userId)
    userInfo.value.departments = data
  } catch (error) {
    console.error('获取部门信息失败:', error)
  }
}

// 获取用户岗位信息
const getPositions = async () => {
  try {
    const { data } = await getUserPositions(userId)
    userInfo.value.positions = data
  } catch (error) {
    console.error('获取岗位信息失败:', error)
  }
}

// 获取操作日志
const getLogs = async () => {
  logLoading.value = true
  try {
    const params = {
      ...logSearchForm,
      startDate: logSearchForm.dateRange?.[0],
      endDate: logSearchForm.dateRange?.[1],
      page: logPage.current,
      size: logPage.size
    }
    const { data } = await getUserLogs(userId, params)
    logList.value = data.list
    logPage.total = data.total
  } catch (error) {
    console.error('获取操作日志失败:', error)
  } finally {
    logLoading.value = false
  }
}

// 获取登录历史
const getLoginHistory = async () => {
  loginLoading.value = true
  try {
    const params = {
      ...loginSearchForm,
      startDate: loginSearchForm.dateRange?.[0],
      endDate: loginSearchForm.dateRange?.[1],
      page: loginPage.current,
      size: loginPage.size
    }
    const { data } = await getUserLoginHistory(userId, params)
    loginList.value = data.list
    loginPage.total = data.total
  } catch (error) {
    console.error('获取登录历史失败:', error)
  } finally {
    loginLoading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getUserStatistics(userId)
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取安全设置
const getSecuritySettings = async () => {
  try {
    const { data } = await getUserSecuritySettings(userId)
    Object.assign(securitySettings, data)
  } catch (error) {
    console.error('获取安全设置失败:', error)
  }
}

// 获取最近登录记录
const getRecentLogins = async () => {
  try {
    const { data } = await getUserLoginHistory(userId, { page: 1, size: 5 })
    recentLogins.value = data.list
  } catch (error) {
    console.error('获取最近登录记录失败:', error)
  }
}

// 获取设备列表
const getDeviceList = async () => {
  try {
    const { data } = await getUserDevices(userId)
    deviceList.value = data
  } catch (error) {
    console.error('获取设备列表失败:', error)
  }
}

// 初始化登录趋势图
const initLoginTrendChart = () => {
  if (!loginTrendChartRef.value) return
  
  loginTrendChart = echarts.init(loginTrendChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [5, 7, 3, 8, 6, 4, 9],
      type: 'line',
      smooth: true,
      areaStyle: {}
    }]
  }
  loginTrendChart.setOption(option)
}

// 初始化活跃度分析图
const initActiveAnalysisChart = () => {
  if (!activeAnalysisChartRef.value) return
  
  activeAnalysisChart = echarts.init(activeAnalysisChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [2, 1, 0, 5, 8, 6, 7, 4],
      type: 'bar'
    }]
  }
  activeAnalysisChart.setOption(option)
}

// 初始化设备分布图
const initDeviceDistChart = () => {
  if (!deviceDistChartRef.value) return
  
  deviceDistChart = echarts.init(deviceDistChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: [
        { value: 60, name: 'Chrome' },
        { value: 20, name: 'Firefox' },
        { value: 15, name: 'Safari' },
        { value: 5, name: '其他' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  deviceDistChart.setOption(option)
}

// 初始化地区分布图
const initLocationDistChart = () => {
  if (!locationDistChartRef.value) return
  
  locationDistChart = echarts.init(locationDistChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 40, name: '北京' },
        { value: 25, name: '上海' },
        { value: 20, name: '广州' },
        { value: 15, name: '其他' }
      ]
    }]
  }
  locationDistChart.setOption(option)
}

// 监听图表类型变化
watch([loginTrendType, activeAnalysisType], () => {
  // 重新获取数据并更新图表
  getStatistics()
})

// 监听窗口大小变化
const handleResize = () => {
  loginTrendChart?.resize()
  activeAnalysisChart?.resize()
  deviceDistChart?.resize()
  locationDistChart?.resize()
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 编辑用户
const handleEdit = () => {
  Object.keys(userForm).forEach(key => {
    userForm[key] = userInfo.value[key]
  })
  dialogVisible.value = true
}

// 提交编辑
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    await updateUser({ id: userId, ...userForm })
    ElMessage.success('更新成功')
    dialogVisible.value = false
    getUserInfo()
  } catch (error) {
    console.error('更新用户失败:', error)
  }
}

// 删除用户
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确认删除该用户吗？', '提示', {
      type: 'warning'
    })
    await deleteUser(userId)
    ElMessage.success('删除成功')
    router.back()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
    }
  }
}

// 操作日志搜索
const handleLogSearch = () => {
  logPage.current = 1
  getLogs()
}

// 操作日志重置
const handleLogReset = () => {
  Object.keys(logSearchForm).forEach(key => {
    logSearchForm[key] = ''
  })
  handleLogSearch()
}

// 登录历史搜索
const handleLoginSearch = () => {
  loginPage.current = 1
  getLoginHistory()
}

// 登录历史重置
const handleLoginReset = () => {
  Object.keys(loginSearchForm).forEach(key => {
    loginSearchForm[key] = ''
  })
  handleLoginSearch()
}

// 操作日志分页
const handleLogSizeChange = (val) => {
  logPage.size = val
  getLogs()
}

const handleLogCurrentChange = (val) => {
  logPage.current = val
  getLogs()
}

// 登录历史分页
const handleLoginSizeChange = (val) => {
  loginPage.size = val
  getLoginHistory()
}

const handleLoginCurrentChange = (val) => {
  loginPage.current = val
  getLoginHistory()
}

// 获取操作类型标签
const getLogTypeTag = (type) => {
  const typeMap = {
    login: 'info',
    create: 'success',
    update: 'warning',
    delete: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取操作类型标签文本
const getLogTypeLabel = (type) => {
  const typeMap = {
    login: '登录',
    create: '新增',
    update: '修改',
    delete: '删除'
  }
  return typeMap[type] || type
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    await changeUserPassword({
      userId,
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    Object.keys(passwordForm).forEach(key => {
      passwordForm[key] = ''
    })
  } catch (error) {
    console.error('修改密码失败:', error)
  }
}

// 修改手机
const handleChangePhone = () => {
  // TODO: 实现手机修改逻辑
  ElMessage.info('手机修改功能开发中')
}

// 修改邮箱
const handleChangeEmail = () => {
  // TODO: 实现邮箱修改逻辑
  ElMessage.info('邮箱修改功能开发中')
}

// 切换登录保护
const handleToggleLoginProtection = async (value) => {
  try {
    await updateUserSecuritySettings(userId, { loginProtection: value })
    ElMessage.success(`${value ? '开启' : '关闭'}登录保护成功`)
  } catch (error) {
    console.error('更新登录保护设置失败:', error)
    securitySettings.loginProtection = !value
  }
}

// 切换登录提醒
const handleToggleLoginAlert = async (value) => {
  try {
    await updateUserSecuritySettings(userId, { loginAlert: value })
    ElMessage.success(`${value ? '开启' : '关闭'}登录提醒成功`)
  } catch (error) {
    console.error('更新登录提醒设置失败:', error)
    securitySettings.loginAlert = !value
  }
}

// 管理设备
const handleManageDevices = async () => {
  await getDeviceList()
  deviceDialogVisible.value = true
}

// 强制下线
const handleForceLogout = async (device) => {
  try {
    await ElMessageBox.confirm('确认强制该设备下线吗？', '提示', {
      type: 'warning'
    })
    await forceUserLogout(device.id)
    ElMessage.success('强制下线成功')
    getDeviceList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('强制下线失败:', error)
    }
  }
}

// 查看全部登录记录
const handleViewAllLogins = () => {
  activeTab.value = 'login-history'
}

// 手机号脱敏
const maskPhone = (phone) => {
  if (!phone) return '-'
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return '-'
  const [name, domain] = email.split('@')
  return `${name.charAt(0)}***@${domain}`
}

onMounted(() => {
  getUserInfo()
  getDepartments()
  getPositions()
  getLogs()
  getLoginHistory()
  getStatistics()
  getSecuritySettings()
  getRecentLogins()
  nextTick(() => {
    initLoginTrendChart()
    initActiveAnalysisChart()
    initDeviceDistChart()
    initLocationDistChart()
  })
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  loginTrendChart?.dispose()
  activeAnalysisChart?.dispose()
  deviceDistChart?.dispose()
  locationDistChart?.dispose()
})
</script>

<style lang="scss" scoped>
.user-detail {
  padding: 20px;

  .detail-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;

        .title {
          font-size: 16px;
          font-weight: bold;
        }
      }

      .header-right {
        display: flex;
        gap: 10px;
      }
    }

    .section-title {
      margin: 20px 0 10px;
      font-size: 14px;
      font-weight: bold;
      color: #606266;
    }

    .search-bar {
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.statistics-cards {
  margin-bottom: 20px;

  .statistics-card {
    .card-header {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 14px;
      color: #606266;
    }

    .card-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin: 10px 0;
    }

    .card-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #909399;

      .trend {
        display: flex;
        align-items: center;
        gap: 2px;

        &.up {
          color: #67c23a;
        }

        &.down {
          color: #f56c6c;
        }
      }
    }
  }
}

.statistics-charts {
  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 300px;
    }
  }
}

.mt-20 {
  margin-top: 20px;
}

.security-score {
  margin-bottom: 20px;

  .score-card {
    .score-header {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 16px;
      font-weight: bold;
    }

    .score-content {
      display: flex;
      align-items: center;
      gap: 40px;
      padding: 20px 0;

      .score-circle {
        width: 200px;
      }

      .score-value {
        text-align: center;

        .number {
          font-size: 36px;
          font-weight: bold;
          color: #303133;
        }

        .label {
          font-size: 14px;
          color: #909399;
          margin-left: 5px;
        }
      }

      .score-tips {
        flex: 1;

        .main-tip {
          font-size: 16px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 10px;
        }

        .sub-tip {
          font-size: 14px;
          color: #606266;
          margin-bottom: 15px;
        }

        .tip-list {
          list-style: none;
          padding: 0;
          margin: 0;

          li {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;

            .el-icon {
              color: #E6A23C;
            }
          }
        }
      }
    }
  }
}

.security-settings {
  margin-bottom: 20px;

  .settings-card {
    .setting-item {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .setting-info {
        .label {
          display: block;
          font-size: 14px;
          color: #303133;
          margin-bottom: 5px;
        }

        .value {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

.recent-logins {
  .logins-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style> 